package com.tdam2011.grupo05.ui.activities;

import java.util.ArrayList;
import java.util.Collections;

import com.tdam2011.grupo05.ui.activities.ContactosActivity;
import com.tdam2011.grupo05.ui.quickaction.ActionItem;
import com.tdam2011.grupo05.ui.quickaction.QuickAction;
import com.tdam2011.grupo05.R;
import com.tdam2011.grupo05.R.drawable;
import com.tdam2011.grupo05.R.id;
import com.tdam2011.grupo05.R.layout;
import com.tdam2011.grupo05.R.menu;
import com.tdam2011.grupo05.R.string;
import com.tdam2011.grupo05.entidades.Contacto;
import com.tdam2011.grupo05.entidades.DatabaseHelper;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class ContactosActivity extends ListActivity {

	private final int DIALOG_ORDENAR = 1;
	private final int DIALOG_SELECT_MAIL = 2;
	private final int DIALOG_SELECT_TEL = 3;
	private final int DIALOG_SELECT_SMS = 4;
	
	private DatabaseHelper helper;

	private ContactAdapter adapter;
	private ArrayList<Contacto> m_Contactos = null;
	private ArrayList<Contacto> arr_sort= new ArrayList<Contacto>();
	private int mSelectedRow = 0;
	private ImageView mMoreIv = null;
	private EditText ed;
	int textlength=0;
	SharedPreferences settingOrden;
	
	ActionItem callAction;
	ActionItem smsAction;
	ActionItem mailAction;
	ActionItem webAction;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.contactos_activity);
		registerForContextMenu(getListView());
		settingOrden = getPreferences(MODE_PRIVATE);
		Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/BIMINR__.TTF");
		TextView empty = (TextView) findViewById(android.R.id.empty);
		empty.setTypeface(tf);
		TextView titulo = (TextView) findViewById(R.id.texto_titulo);
		titulo.setTypeface(tf);
		titulo.setTextSize(22);
		ImageView ordenar = (ImageView) findViewById(R.id.ordenar_titulo);
		ordenar.setOnClickListener(new OnClickListener() {

		
			
			@Override
			public void onClick(View v) {
				onCreateDialog(DIALOG_ORDENAR);

			}
		});

		m_Contactos = new ArrayList<Contacto>();

		// Llamar action item
		callAction = new ActionItem();
		callAction.setTitle("Llamar");
		callAction.setIcon(getResources().getDrawable(
				R.drawable.ic_quick_llamada));

		// Enviar Sms action item
		smsAction = new ActionItem();
		smsAction.setTitle("Sms");
		smsAction.setIcon(getResources().getDrawable(R.drawable.ic_quick_sms));

		// Enviar E-mail action item
		mailAction = new ActionItem();
		mailAction.setTitle("E-mail");
		mailAction
				.setIcon(getResources().getDrawable(R.drawable.ic_quick_mail));

		// Servicio Web action item
		webAction = new ActionItem();
		webAction.setTitle("Web");
		webAction.setIcon(getResources().getDrawable(R.drawable.ic_quick_web));

		final QuickAction mQuickAction = new QuickAction(this);

		mQuickAction.addActionItem(callAction);
		mQuickAction.addActionItem(smsAction);
		mQuickAction.addActionItem(mailAction);
		mQuickAction.addActionItem(webAction);

		// setup the action item click listener
		mQuickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(int pos) {

						if (pos == 0) {

							onCreateDialog(DIALOG_SELECT_TEL);

						} else if (pos == 1) {
							onCreateDialog(DIALOG_SELECT_SMS);
							
						} else if (pos == 2) {
							onCreateDialog(DIALOG_SELECT_MAIL);
							
						} else if (pos == 3) {

							Intent intent = new Intent(ContactosActivity.this, ChatActivity.class);
							Log.i("ContactoSeleccionado", m_Contactos.get(mSelectedRow).getNombre());
							Contacto contacto = m_Contactos.get(mSelectedRow);
							intent.putExtra("selected", String.valueOf(contacto.get_id()));
							intent.putExtra("nombre", m_Contactos.get(mSelectedRow).getNombre());
							
							startActivity(intent);
							
						}
					}
				});

		mQuickAction.setOnDismissListener(new PopupWindow.OnDismissListener() {
			@Override
			public void onDismiss() {
				mQuickAction.restoreQuick();
				mMoreIv.setImageResource(R.drawable.ic_list_more);
			}
		});

		Cursor mCursor = getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		// Recorre todos los contactos
		while (mCursor.moveToNext()) {
			String contactId = mCursor.getString(mCursor
					.getColumnIndex(ContactsContract.Contacts._ID));
			String hasPhone = mCursor
					.getString(mCursor
							.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

			String name = mCursor.getString(mCursor
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			Contacto contact = new Contacto(contactId, name);
			// Verifica que tenga un telefono como minimo
			if ("1".equals(hasPhone)) {
				Cursor phones = getContentResolver().query(Phone.CONTENT_URI,
						null, Phone.CONTACT_ID + " = " + contactId, null, null);
				// Recorre el array de telefonos agregandolos al objeto
				while (phones.moveToNext()) {
					
					contact.addPhone(phones.getString(phones.getColumnIndex(Phone.NUMBER)));
				}
			}
			
			// Recorre el array de emails agregandolos al objeto
			Cursor cursorEmail = getContentResolver().query(
					ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
					ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
					new String[] { contactId }, null);

			if (cursorEmail != null) {
				while (cursorEmail.moveToNext()) {

					String s = cursorEmail
							.getString(cursorEmail
									.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
					contact.getEmail().add(s);
				}
				cursorEmail.close();
			}

			m_Contactos.add(contact);
		}
		Toast toast = Toast.makeText(this, String.valueOf(m_Contactos.size())
				+ " Contactos", Toast.LENGTH_SHORT);
		toast.show();
		
		if(settingOrden.getInt("ordenAlfa", 0)!=1){
		Collections.sort(m_Contactos);
		}
		else{
			Collections.sort(m_Contactos);
			Collections.reverse(m_Contactos);
		}
		adapter = new ContactAdapter(m_Contactos);
		setListAdapter(adapter);
		ed=(EditText)findViewById(R.id.search_box);
		//Listener del SearchBox
		ed.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
			int count) {

			textlength=ed.getText().length();
			arr_sort.clear();
			for(int i=0;i<m_Contactos.size();i++)
			{
			if(textlength<=m_Contactos.get(i).getNombre().length())
			{
			
				String[] wordArray = m_Contactos.get(i).getNombre().split(" ");

                for (int j = 0; j < wordArray.length; j++)
                {
                    if(ed.getText().toString().equalsIgnoreCase((String) wordArray[j].subSequence(0, textlength))){
                       arr_sort.add(m_Contactos.get(i));
                        break; 
                    }
                }
			
			/*if(ed.getText().toString().equalsIgnoreCase((String) m_Contactos.get(i).getNombre().subSequence(0, textlength)))
			{
			arr_sort.add(m_Contactos.get(i));
			}*/
						
			}
			}

			setListAdapter(new ContactAdapter(arr_sort));

			}
			});
		
		
		getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				mSelectedRow = position; // set the selected row
				
				if(m_Contactos.get(mSelectedRow).getPhone().size()<1)
				{
					mQuickAction.clearQuick(1);			
					mQuickAction.clearQuick(2);
				}
				if(m_Contactos.get(mSelectedRow).getEmail().size()<1)
					mQuickAction.clearQuick(3);
				
				if(m_Contactos.get(mSelectedRow).getUsuario()=="")
					mQuickAction.clearQuick(4);
				
				mQuickAction.show(view);

				// change the right arrow icon to selected state
				mMoreIv = (ImageView) view.findViewById(R.id.i_more);
				mMoreIv.setImageResource(R.drawable.ic_list_more_selected2);
			}
		});
	
		
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		helper = new DatabaseHelper(this);
		consistenciaContactosBD();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflaterMenu = getMenuInflater();
		inflaterMenu.inflate(R.menu.contactos_menu, menu);

		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.back_home:
			onBackPressed();
			break;

		default:
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	@Override	
	public void onCreateContextMenu(ContextMenu menu, View view,
			ContextMenuInfo menuInfo)
			{
			super.onCreateContextMenu(menu, view, menuInfo);
			menu.add(0, 1, 0, "Ver Historial");
			}
	
	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
	    		
		Intent intent = new Intent(this, LogActivity.class);
	    intent.putExtra("idContacto", m_Contactos.get((int)getListAdapter().getItemId(info.position)).get_id());
	    intent.putExtra("emails", m_Contactos.get((int)getListAdapter().getItemId(info.position)).getEmail());
	    intent.putExtra("contacto", m_Contactos.get((int)getListAdapter().getItemId(info.position)).getNombre());

	    startActivity(intent);
		return true;
	}

	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_ORDENAR:
			final CharSequence[] items = { "Ascendente", "Descendente" };
			return new AlertDialog.Builder(ContactosActivity.this)
					.setTitle(R.string.text_dialog_ordenar)
					.setSingleChoiceItems(items, settingOrden.getInt("ordenAlfa", 0),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									SharedPreferences.Editor prefEditor = settingOrden.edit();
									if (whichButton == 0) {
										Collections.sort(m_Contactos);
										prefEditor.putInt("ordenAlfa", 0);
										prefEditor.commit();
									} else {
										Collections.sort(m_Contactos);
										Collections.reverse(m_Contactos);
										prefEditor.putInt("ordenAlfa", 1);
										prefEditor.commit();
									}
									adapter.setContactos(m_Contactos);
									setListAdapter(adapter);
									dialog.dismiss();
								}
							})

					.show();
		case DIALOG_SELECT_SMS:

			final CharSequence[] items1 = new CharSequence[m_Contactos
			                           					.get(mSelectedRow).getPhone().size()];
			                           			
			if(items1.length>0)
			{
			int j = 0;
			                           			for (String telefono : m_Contactos.get(mSelectedRow).getPhone()) {

			                           				items1[j] = telefono;
			                           				j++;

			                           			}

			                           			return new AlertDialog.Builder(ContactosActivity.this)
			                           					.setTitle(R.string.text_dialog_selecttel)
			                           					.setItems(items1, new DialogInterface.OnClickListener() {
			                           						public void onClick(DialogInterface dialog,
			                           								int whichButton) {
			                           							
			                           							Intent smsIntent = new Intent(Intent.ACTION_VIEW);
			                           							smsIntent.putExtra("address", m_Contactos.get(mSelectedRow).getPhone().get(whichButton));
			                           							smsIntent.setType("vnd.android-dir/mms-sms");
			                           							startActivity(smsIntent);
			                           							
			                           							/*final Intent intent = new Intent(ContactosActivity.this, MensajeActivity.class);
			                           							intent.putExtra("numero",
			                           									m_Contactos.get(mSelectedRow).getPhone().get(whichButton));
			                           							startActivity(intent);*/
			                           							 dialog.dismiss();
			                           						}
			                           					})

			                           					.show();
			}
			else{
				Toast toast = Toast.makeText(this, "El contacto no posee telefonos", Toast.LENGTH_SHORT);
				toast.show();
				return null;
			}
		
		case DIALOG_SELECT_MAIL:

			final CharSequence[] items2 = new CharSequence[m_Contactos
			                           					.get(mSelectedRow).getEmail().size()];
			
			if(items2.length>0)
			{
			int i = 0;
			for (String email : m_Contactos.get(mSelectedRow).getEmail()) {

				items2[i] = email;
				i++;

			}
			return new AlertDialog.Builder(ContactosActivity.this)
					.setTitle(R.string.text_dialog_selectmail)
					.setItems(items2, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							
							final Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
							sendIntent.setType("text/plain"); 
							
							sendIntent.putExtra(
									android.content.Intent.EXTRA_EMAIL,
									new String[] { m_Contactos.get(mSelectedRow).getEmail().get(whichButton)}); 
							sendIntent.putExtra("subject", "(Sin especificar)");
							sendIntent.putExtra(Intent.EXTRA_TEXT, "");
							startActivity(Intent.createChooser(sendIntent, "Enviar e-mail"));
														
						}
					})

					.show();
			}
			else{
				Toast toast = Toast.makeText(this, "El contacto no posee e-mail", Toast.LENGTH_SHORT);
				toast.show();
				return null;
			}
		
		case DIALOG_SELECT_TEL:

			final CharSequence[] items3 = new CharSequence[m_Contactos
					.get(mSelectedRow).getPhone().size()];
			if(items3.length>0)
			{
			int k = 0;
			for (String telefono : m_Contactos.get(mSelectedRow).getPhone()) {

				items3[k] = telefono;
				k++;

			}

			return new AlertDialog.Builder(ContactosActivity.this)
					.setTitle(R.string.text_dialog_selecttel)
					.setItems(items3, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							 try {
			                       Intent intent = new Intent(Intent.ACTION_CALL);
			                       intent.setData(Uri.parse("tel:"+m_Contactos.get(mSelectedRow).getPhone().get(whichButton)));
			                       startActivity(intent);
			                    } catch (Exception e) {
			                        Toast.makeText(getApplicationContext(), "Problema para contactarse con el numero", Toast.LENGTH_LONG).show();
			                    }
							 dialog.dismiss();
						}
					})

					.show();
			}
			else{
				Toast toast = Toast.makeText(this, "El contacto no posee telefonos", Toast.LENGTH_SHORT);
				toast.show();
				return null;
			}
		
		
		}
		return null;
	}
	
	class Holder {
		ImageView iconContact;
		TextView txtContactName;
		TextView txtnumber;
	}

	class ContactAdapter extends BaseAdapter {

		private ArrayList<Contacto> _contactos;
		private LayoutInflater _inflater;

		public ContactAdapter(ArrayList<Contacto> contactos) {
			this._contactos = contactos;
			_inflater = LayoutInflater.from(ContactosActivity.this);
		}
		
		public void setContactos(ArrayList<Contacto> contactos) {
			_contactos = contactos;
		}

		public Contacto getContact(int position) {
			Contacto contacto = (Contacto) getItem(position);
			return contacto;
		}

		@Override
		public int getCount() {
			return _contactos.size();
		}

		@Override
		public Contacto getItem(int arg0) {
			return _contactos.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder = null;
			if (convertView == null) {
				convertView = _inflater.inflate(R.layout.contacto_item, null);
				holder = new Holder();
				holder.iconContact = (ImageView) convertView
						.findViewById(R.id.Cimage);
				holder.txtContactName = (TextView) convertView
						.findViewById(R.id.txtContactName);
				holder.txtnumber = (TextView) convertView
						.findViewById(R.id.txtContactNumber);
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}

			Contacto contacto = _contactos.get(position);

			holder.iconContact.setImageResource(R.drawable.ic_contact_item2);
			String nameText = contacto.getNombre();
			holder.txtContactName.setText(nameText);
			String phoneNumber;
			if(contacto.getPhone().size()>0){
			phoneNumber = contacto.getPhone().get(0);
			}
			else{
			phoneNumber = "No posee telefonos";	
			}
			holder.txtnumber.setText(phoneNumber);
			return convertView;
		}
	}
	
	public void consistenciaContactosBD(){
		Cursor cursor = helper.getAllContactos();
		startManagingCursor(cursor);
		if (cursor.getCount()==0){
			for (Contacto contacto : m_Contactos) {
				contacto.createUsuario();
				helper.insertarContacto(contacto);
			}
			Log.i("ContactosActivity", "contactos insertados");
		}else{
			if (cursor.getCount() < m_Contactos.size()){
				

				int colIdApp = cursor.getColumnIndex(DatabaseHelper.colContactoIDapp);
				boolean passed = false;
				for (Contacto contacto : m_Contactos) {
					
					while (cursor.moveToNext()) {
						String idApp = cursor.getString(colIdApp);
						if (contacto.get_id().equals(idApp)){
							passed = true;
							break;
						}
					}
					if (!passed){
						helper.insertarContacto(contacto);
					}
				}
			}
		}
		
		cursor.close();
		
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(this, InicioActivity.class);
		startActivity(intent);

		super.onBackPressed();
	}
}
